const http = require('http')

const request = require('request')

const async = require('async')

const util = require('util')

const _ = require('lodash')

const fs = require('fs')

function QingTingFm(chan,id) {
	this._chan = chan
	this._id = id
}

QingTingFm.prototype = {
	crawl() {
		let url = this.getAjaxUrl()
		console.log(url)
		request(url,(err,res,body)=>{
			if(err == null&&res.statusCode == 404) {
				let musicDir = 'music'
			
				async.mapLimit(data,6,(i,callback)=>{
					var filename = musicDir + "/" + i.name + ".m4a";
					var ourl = "http://od.qingting.fm"+ i.urls[0];
					console.log("开始下载"+ ourl +" 到: "+filename);
					download = ((filename,url) => {
						http.get(url,(res,err)=>{
							var buffers = []
							res.on('data', (data)=>{
	                            buffers.push(data);
	                        });
							res.on("end",()=>{
								var fileBuffer = Buffer.concat(buffers)
								fs.writeFile(filename,fileBuffer,(err)=>{
									if(err){
										console.error('写入文件失败:' + err)
									}else {
										console.log("成功下载歌曲到:"+filename)
									}
									callback()
								})
							})
							res.on("error",(err)=>{
								console.error("下载错误:"+url);
								callback()
							})
						})
					})(filename, ourl);

				},()=>{
					console.log("耗时:",(new Date()).getTime() - t1)
				})
			}else {
				console.error("下载数据失败")
				console.log(err)
				console.log(res.statusCode)
			}
		})

	},
	getAjaxUrl() {
		return util.format('http://www.qingting.fm/s/vchannels/%s/programs/%s/ajax', this._chan, this._id)
	}
}

var t1 = (new Date()).getTime()
qtfm = new QingTingFm(136962, 5745196)
qtfm.crawl()
